package com.zcx.qshop.fragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.zcx.helper.activity.AppFragment;
import com.zcx.helper.bound.BoundView;
import com.zcx.helper.bound.BoundViewHelper;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.helper.util.UtilToast;
import com.zcx.qshop.R;
import com.zcx.qshop.QSApplication;
import com.zcx.qshop.action.LoginAction;
import com.zcx.qshop.activity.ActivitvActivity;
import com.zcx.qshop.activity.CityActivity;
import com.zcx.qshop.activity.CommodityDetailActivity;
import com.zcx.qshop.activity.SearchActivity;
import com.zcx.qshop.adapter.HomeAdapter;
import com.zcx.qshop.conn.JsonAreaAsyGet;
import com.zcx.qshop.conn.JsonIndexAsyGet;
import com.zcx.qshop.conn.JsonUserAsyGet;
import com.zcx.qshop.entity.Good;
import com.module.pull.PullToRefreshBase;
import com.module.pull.PullToRefreshListView;
import com.zcx.qshop.view.HomeBannerView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2015/11/9.
 */
public class HomeFragment extends AppFragment implements View.OnClickListener{

    public static OnCityChangeCallBack OnCityChangeCallBack;

    @BoundView(R.id.home_address) private TextView address;

    @BoundView(R.id.home_search) private View search;

    @BoundView(R.id.home_banner_view) private HomeBannerView homeBannerView;

    @BoundView(R.id.home_falg_group) private ViewGroup falgGroup;

    @BoundView(R.id.home_advert_group) private ViewGroup advertGroup;

    @BoundView(R.id.home_pull_to_refresh) private PullToRefreshListView pullToRefresh;

    private List<JsonIndexAsyGet.GoodDouble> list = new ArrayList<>();

    private HomeAdapter homeAdapter;

    private JsonIndexAsyGet.Info info;

    private JsonIndexAsyGet jsonIndexAsyGet = new JsonIndexAsyGet("", "", "", new AsyCallBack<JsonIndexAsyGet.Info>(){

        @Override
        public void onSuccess(String toast, int type, JsonIndexAsyGet.Info info) throws Exception {

            HomeFragment.this.info = info;

            if(type == 1 || type == 0){

                homeBannerView.setItems(info.banners);

                for(int i = 0 ; i < falgGroup.getChildCount() ; i ++){

                    setFalg(info.flags.get(i), (ViewGroup) falgGroup.getChildAt(i));

                }

                for(int i = 0 ; i < advertGroup.getChildCount() ; i ++){

                    setAdverts(info.adverts.get(i), (SimpleDraweeView) advertGroup.getChildAt(i));

                }

                list.clear();

            }

            list.addAll(info.enjoyDoubles);

            if(type == 1 || type == 0){

                homeAdapter.notifyDataSetInvalidated();

            }else{

                homeAdapter.notifyDataSetChanged();

            }

            if(type == 0){

                pullToRefresh.setVisibility(View.VISIBLE);

            }

        }

        @Override
        public void onEnd(String toast, int type) throws Exception {

            if(type == 1 || type == 2){

                pullToRefresh.onPullUpRefreshComplete();

                pullToRefresh.onPullDownRefreshComplete();

            }

        }

        private void setFalg(final JsonIndexAsyGet.Flag falg, ViewGroup viewGroup){

            try{

//                ((SimpleDraweeView)viewGroup.getChildAt(0)).setImageURI(Uri.parse(falg.picurl));

                ((SimpleDraweeView)viewGroup.getChildAt(0)).setImageURI(Uri.parse("http://120.27.113.249/Public/Uploads/20151229/pic_5681e05aee8e5.png"));

                ((TextView)viewGroup.getChildAt(1)).setText(falg.name);

                viewGroup.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        JsonIndexAsyGet.Advert advert = new JsonIndexAsyGet.Advert();

                        advert.title = falg.name;

                        advert.type = falg.info;

                        startVerifyActivity(ActivitvActivity.class, new Intent().putExtra("Advert", advert));

                    }

                });

            }catch (Exception e){}

        }

        private void setAdverts(final JsonIndexAsyGet.Advert advert, SimpleDraweeView simpleDraweeView){

            try{

                simpleDraweeView.setImageURI(Uri.parse(advert.picurl));

                simpleDraweeView.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        startVerifyActivity(ActivitvActivity.class, new Intent().putExtra("Advert", advert));

                    }

                });

            }catch (Exception e){}

        }

    });

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = BoundViewHelper.boundView(this, QSApplication.ScaleScreenHelper.loadView((ViewGroup) inflater.inflate(R.layout.fragment_home, null)));

        pullToRefresh.setPullRefreshEnabled(true);

        pullToRefresh.setPullLoadEnabled(false);

        pullToRefresh.setScrollLoadEnabled(true);

        pullToRefresh.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {

            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {

                jsonIndexAsyGet.page = "1";

                jsonIndexAsyGet.execute(getActivity(), false, 1);

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {

                if (info.ispage.equals("0")) {

                    UtilToast.show(getActivity(), "没有数据");

                    pullToRefresh.onPullUpRefreshComplete();

                    pullToRefresh.onPullDownRefreshComplete();

                } else {

                    jsonIndexAsyGet.page = info.nextpage;

                    jsonIndexAsyGet.execute(getActivity(), false, 2);

                }

            }

        });

        final ListView listView = pullToRefresh.getRefreshableView();

        listView.setDivider(null);

        listView.setVerticalScrollBarEnabled(false);

        listView.addHeaderView(BoundViewHelper.boundView(this, QSApplication.ScaleScreenHelper.loadView((ViewGroup) inflater.inflate(R.layout.header_home, null))));

        listView.setAdapter(homeAdapter = new HomeAdapter(getActivity(), list) {

            @Override
            protected void onDetail(Good good) {

                startActivity(new Intent(getActivity(), CommodityDetailActivity.class).putExtra("Good", good));

            }

        });

        homeBannerView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                if (event.getAction() == MotionEvent.ACTION_UP) {

                    listView.requestDisallowInterceptTouchEvent(false);

                } else {

                    listView.requestDisallowInterceptTouchEvent(true);

                }

                return false;

            }

        });

        address.setOnClickListener(this);

        search.setOnClickListener(this);

        QSApplication.LoginAction.addOnLoginStateListener(new LoginAction.OnLoginStateListener() {

            @Override
            public void onLogin(JsonUserAsyGet.Info info) {

                loadDate(info.uid, QSApplication.QSPreferences.readCity());

            }

            @Override
            public void onExit() {

                loadDate("", QSApplication.QSPreferences.readCity());

            }

            private void loadDate(String uid, JsonAreaAsyGet.Area area) {

                if (area.code.equals("")) {

                    onClick(address);

                } else {

                    address.setText(area.name);

                    jsonIndexAsyGet.page = "1";

                    jsonIndexAsyGet.uid = uid;

                    jsonIndexAsyGet.areaid = area.code;

                    jsonIndexAsyGet.execute(getActivity());

                }

            }

        });

        return view;

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){

            case R.id.home_address:

                OnCityChangeCallBack = new OnCityChangeCallBack() {

                    @Override
                    public void onCityChange(JsonAreaAsyGet.Area area) {

                        QSApplication.QSPreferences.saveCity(area);

                        address.setText(area.name);

                        jsonIndexAsyGet.page = "1";

                        jsonIndexAsyGet.areaid = area.code;

                        jsonIndexAsyGet.execute(getActivity());

                        if (ClassifyFragment.onCityChangeCallBack != null) {

                            ClassifyFragment.onCityChangeCallBack.onCityChange(area);

                        }

                    }

                };

                startVerifyActivity(CityActivity.class);

                break;

            case R.id.home_search:

                startVerifyActivity(SearchActivity.class);

                break;

        }

    }

    public interface OnCityChangeCallBack{

        void onCityChange(JsonAreaAsyGet.Area area);

    }

}